package com.cspg.ssss.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cspg.ssss.config.FileStoreConfig;
import com.cspg.ssss.domain.*;
import com.cspg.ssss.job.DaiBanJob;
import com.cspg.ssss.service.*;
import com.cspg.ssss.util.DateUtil;
import com.cspg.ssss.vo.PageInfoVo;
import com.cspg.ssss.vo.ResultVo;
import com.cspg.ssss.vo.ResultVoUtil;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;


@RestController
@RequestMapping("/grade")
public class AddScoreApplyController {

    private static final Logger log = LoggerFactory.getLogger(AddScoreApplyController.class);

    @Autowired
    ScoreAddApplyService scoreAddApplyService;
    @Autowired
    ApproveService approveService;
    @Autowired
    FileStoreConfig fileStoreConfig;
    @Autowired
    GradeRoleUserService gradeRoleUserService;

    @Autowired
    ObjHistoryService objHistoryService;

    @Autowired
    ApproveUserSelectService approveUserSelectService;

    @Autowired
    WxDepartmentService wxDepartmentService;

    @Autowired
    CheckItemService checkItemService;

    @Autowired
    CheckBatchService checkBatchService;

    @Autowired
    WxSendMsgService wxSendMsgService;

    @Autowired
    DaiBanService daiBanService;

    @PostMapping("/uploadfile")
    public ResultVo updateFileTest(@RequestParam("file") MultipartFile file) {
        JSONObject retObj = new JSONObject();
        retObj.put("file_name", file.getOriginalFilename());
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        File localFile = new File(fileStoreConfig.getRoot_path() + filename + "." + suffix);
        try {
            file.transferTo(localFile);
        } catch (Exception ex) {
            ResultVo errVo = ResultVoUtil.error("9999", ex.getMessage());
            return errVo;
        }
        String fullUrl = fileStoreConfig.getRoot_url() + filename + "." + suffix;
        retObj.put("file_url", fullUrl);
        ResultVo retVo = ResultVoUtil.success("success", retObj);
        return retVo;
    }

/*    @GetMapping("/getAddApplyList")
    public ResultVo getAddApplyList(@RequestParam Map<String,String> req){
        String opType = req.get("op");
        String userid = req.get("userid");
        List<ScoreAddApplyEntity> retlist = new ArrayList<ScoreAddApplyEntity>();
        if(opType.equalsIgnoreCase("create")){
            retlist = scoreAddApplyService.getScoreAddApplyListByApplyUser(userid);
        }
        if(opType.equalsIgnoreCase("check")){
            retlist = scoreAddApplyService.getScoreAddApplyListByApproveUser(userid);
        }
        if(opType.equalsIgnoreCase("check_review")){
            retlist = scoreAddApplyService.getScoreAddApplyListByRecheckUser(userid);
        }
        if(opType.equalsIgnoreCase("review")){
            retlist = scoreAddApplyService.getScoreAddApplyListByRecheckUser(userid);
        }
        ResultVo retVo = ResultVoUtil.success("success",retlist);
        return retVo;
    }*/

/*    @GetMapping("/getAddApplyDetail")
    public ResultVo getAddApplyDetail(String applyid){
        JSONObject applyObj = new JSONObject();
        ScoreAddApplyEntity en = scoreAddApplyService.getScoreAddApply(applyid);
        Map<String,GradeApproveEntity> map = approveService.getScoreAddApprovedList(applyid);
        applyObj.put("apply_inst",en);
        applyObj.put("op_check",map.get("op_check"));
        applyObj.put("op_review",map.get("op_review"));
        ResultVo retVo = ResultVoUtil.success("success",applyObj);
        return retVo;
    }*/

    @PostMapping("/updateApplyInst")
    public ResultVo updateApplyInst(@RequestBody JSONObject req) {
        String op = req.getString("op");
        JSONObject applyInst = req.getJSONObject("apply_inst");
        JSONObject opcontent = req.getJSONObject("opcontent");

        CheckBatchInst batchInst = checkBatchService.getCurrentCheckBachInst(Integer.parseInt(applyInst.getString("apply_type")));

        //非评分及审核阶段，不允许加分申请
        if (scoreAddApplyService.getApplyStage(batchInst) >= 1 && op.equals("create")) {
            ResultVo errVo = ResultVoUtil.error("9000", "超出时间期限，不可以加分申请!");
            return errVo;
        }

        ScoreAddApplyEntity sen = new ScoreAddApplyEntity();
        if (applyInst.getString("id").equals("")) {
            sen.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            sen.setApply_time(new Date());
            applyInst.put("id", sen.getId());

            sen.setApply_result(0);
            sen.setBatch_id(batchInst.getId());
        } else {
            sen.setId(applyInst.getString("id"));

        }
        sen.setAsse_dept(applyInst.getString("asse_dept"));
        sen.setCarrier_item(applyInst.getString("carrier_item"));
        sen.setAdd_reson(applyInst.getString("add_reson"));
        sen.setScore(applyInst.getString("score"));
        sen.setUser_id(applyInst.getString("user_id"));
        sen.setUser_name(applyInst.getString("user_name"));

        sen.setFile_name(applyInst.getString("file_name"));
        sen.setFile_url(applyInst.getString("file_url"));
        sen.setApply_type(Integer.parseInt(applyInst.getString("apply_type")));
        JSONObject carrierjsonobj = JSONObject.parseObject(applyInst.getString("carrier_item"));
        sen.setMatters(carrierjsonobj.getString("item"));
        //待办
        BacklogEntity updateBacklog = new BacklogEntity();
        Map<String, Object> map = new HashMap<>();
        map.put("type", "0");
        map.put("problem_id", sen.getId());
        List<BacklogEntity> dbList = daiBanService.selectdb(map);
        if(dbList != null && dbList.size() >0){
            updateBacklog.setId(dbList.get(0).getId());
            updateBacklog.setNewTime("1");
        }
        //通知审核人
        JSONArray arr = opcontent.getJSONArray("receivers");
        StringBuilder idList = new StringBuilder();
        String bmmc = "";
        if (arr != null && (!arr.isEmpty())) {
            for (int i = 0; i < arr.size(); i++) {
                idList.append(";").append(arr.getJSONObject(i).getString("user_id"));
                bmmc = arr.getJSONObject(i).getString("department_displaypath");
            }
        }

        if (op.equals("create")) {
            sen.setApply_dept(applyInst.getString("apply_dept"));
            sen.setApply_status(0);
            scoreAddApplyService.updateScoreAddApply(sen);
            //修改待办
            if(updateBacklog.getId() != null){
                updateBacklog.setDbstatus("0");
                updateBacklog.setBmmc(sen.getApply_dept());
                updateBacklog.setDbman(idList.toString());
                daiBanService.updateBacklog(updateBacklog);
            }else{
                updateBacklog.setTerm("0");
                updateBacklog.setDbstatus("0");
                updateBacklog.setType("0");
                updateBacklog.setCreattime(new Date());
                updateBacklog.setTitle(sen.getAdd_reson());
                updateBacklog.setWtfxr(sen.getUser_name());
                updateBacklog.setWtfxsj(DateUtil.getCurrentDateStr());
                updateBacklog.setProblem_id(sen.getId());
                updateBacklog.setBmmc(sen.getApply_dept());
                updateBacklog.setDbman(idList.toString());
                updateBacklog.setScore_type("1");
                updateBacklog.setCheck_type(String.valueOf(sen.getApply_type()));
                daiBanService.insertBacklog(updateBacklog);
            }

        }

        if (op.equals("feedback_modify")) {
            if (opcontent.getString("approve_result").equals("1")) {
                sen.setApply_status(5);
                sen.setApply_result(0);
                //结束待办
                daiBanService.deleteBacklog(updateBacklog.getId());
            } else {
                sen.setApply_status(0);
                //修改待办
                updateBacklog.setDbstatus("0");
                updateBacklog.setBmmc(sen.getApply_dept());
                updateBacklog.setDbman(idList.toString());
                daiBanService.updateBacklog(updateBacklog);
            }
            scoreAddApplyService.updateScoreAddApply(sen);
        }

        if (op.equals("check")) {//加分审核

            if (opcontent.getString("approve_result").equals("0")) {
                sen.setApply_status(4);
                //修改待办
                updateBacklog.setDbstatus("4");
                updateBacklog.setBmmc(sen.getApply_dept());
                updateBacklog.setDbman(sen.getUser_id());
                daiBanService.updateBacklog(updateBacklog);
            } else {
                if (applyInst.getString("apply_type").equals("0")) {
                    sen.setApply_status(3);
                    //修改待办
                    updateBacklog.setDbstatus("3");
                    updateBacklog.setBmmc(bmmc);
                    updateBacklog.setDbman(idList.toString());
                    daiBanService.updateBacklog(updateBacklog);
                } else {
                    //判断是否本部门内的加分申请，如果是，则审核通过后结束流程，针对单位对部门的加分申请
                    String asse_dept = applyInst.getString("asse_dept");
                    String apply_dept = applyInst.getString("apply_dept");
                    if (asse_dept.equals(apply_dept)) {
                        sen.setApply_result(1);
                        sen.setApply_status(5);
                        //结束待办
                        daiBanService.deleteBacklog(updateBacklog.getId());
                    } else {
                        sen.setApply_status(1);
                        //修改待办
                        updateBacklog.setDbstatus("1");
                        updateBacklog.setBmmc(bmmc);
                        updateBacklog.setDbman(idList.toString());
                        daiBanService.updateBacklog(updateBacklog);
                    }
                }
            }
            scoreAddApplyService.updateScoreAddApply(sen);
        }

        if (op.equals("approve_review")) {//局领导加分审核

            if (opcontent.getString("approve_result").equals("0")) {
                sen.setApply_status(4);
                //修改待办
                updateBacklog.setDbstatus("4");
                updateBacklog.setBmmc(sen.getApply_dept());
                updateBacklog.setDbman(sen.getUser_id());
                daiBanService.updateBacklog(updateBacklog);
            } else {
                sen.setApply_status(1);
                //修改待办
                updateBacklog.setDbstatus("1");
                updateBacklog.setBmmc(bmmc);
                updateBacklog.setDbman(idList.toString());
                daiBanService.updateBacklog(updateBacklog);
            }
            scoreAddApplyService.updateScoreAddApply(sen);
        }

        if (op.equals("review")) {
            if (opcontent.getString("approve_result").equals("1")) {
                sen.setApply_result(1);
            }
            sen.setApply_status(5);
            //结束待办
            daiBanService.deleteBacklog(updateBacklog.getId());
            scoreAddApplyService.updateScoreAddApply(sen);
        }
        //记录审核人
        addApproveUsers(op, opcontent, applyInst);
        //根据状态，发送审核人通知或拒绝通知
        //记录历史
        addOpHistory(op, opcontent, applyInst);

        //发送消息
        sendImMessage(op, opcontent, applyInst);

        ResultVo retVo = ResultVoUtil.success("success", null);
        return retVo;
    }

    /**
     * 查询加分申请列表
     *
     * @param req
     * @return
     */
    @PostMapping("/getAddApplyList")
    public ResultVo getAddApplyList(@RequestBody JSONObject req) {
        log.info("=========================getAddApplyList================");
        PageInfoVo<ScoreAddApplyEntity> retPageVo = new PageInfoVo<ScoreAddApplyEntity>();

        String strPgnum = req.getString("pageNum");
        String strPgsize = req.getString("pageSize");
        String user_id = req.getString("user_id");
        String op = req.getString("op");
        String strApplyStatus = req.getString("apply_status");
        String strApplyType = req.getString("apply_type");
        String matters = req.getString("matters");
        String assessmentDept = req.getString("assessment_dept");

        int pgnum = Integer.parseInt(strPgnum);
        int pgsize = Integer.parseInt(strPgsize);
        int ptype = Integer.parseInt(strApplyType);

        CheckBatchInst batchInst = checkBatchService.getCurrentCheckBachInst(ptype);
        if (batchInst == null) {
            ResultVo retVo = ResultVoUtil.success("无批次", retPageVo);
            return retVo;
        }
        log.info("=========================op=="+op);
        HashMap<String, Object> conditionfiled = new HashMap<String, Object>();
        conditionfiled.put("apply_type", ptype);
        conditionfiled.put("batch_id", batchInst.getId());

        if (strApplyStatus != null && (!strApplyStatus.isEmpty())) {
            int problem_stauts = Integer.parseInt(strApplyStatus);
            conditionfiled.put("apply_status", problem_stauts);
        }

        if (matters != null && (!matters.isEmpty())) {
            List<CheckItem> it = checkItemService.getMatters(matters);
            conditionfiled.put("matters", it.get(0).getItem());
        }

        if (op.equalsIgnoreCase("create")) {
            //根据当前人所在部门进行查询
            HashMap<String, Object> usercondition = new HashMap<String, Object>();
            usercondition.put("userid", user_id);
            List<UserDetailInfoEntity> userList = wxDepartmentService.getDepartmentUserList(usercondition);
            if (userList != null && userList.size() > 0) {
                List<String> departsls = new ArrayList<String>();
                for (int i = 0; i < userList.size(); i++) {
                    departsls.add(userList.get(i).getDepartment_displaypath());
                }
                conditionfiled.put("apply_depts", departsls);
            }
            PageInfo<ScoreAddApplyEntity> retLs = scoreAddApplyService.getScoreAddApplyListByApplyUserPager(pgnum, pgsize, conditionfiled);
            retPageVo.setPageNum(retLs.getPageNum());
            retPageVo.setPageSize(retLs.getPageSize());
            retPageVo.setTotal(retLs.getTotal());
            retPageVo.setList(retLs.getList());
        }

        if (op.equalsIgnoreCase("check")) {
            HashMap<String, Object> approvecondition = new HashMap<String, Object>();
            approvecondition.put("user_id", user_id);
            approvecondition.put("apply_type", ptype);
            approvecondition.put("approve_type", 3);
            approvecondition.put("batch_id", batchInst.getId());

            if (strApplyStatus != null && (!strApplyStatus.isEmpty())) {
                int problem_stauts = Integer.parseInt(strApplyStatus);
                approvecondition.put("apply_status", problem_stauts);
            }

            if (matters != null && (!matters.isEmpty())) {
                approvecondition.put("matters", matters);
            }

            PageInfo<ScoreAddApplyEntity> retLs = scoreAddApplyService.getScoreAddApplyListByApproverPager(pgnum, pgsize, approvecondition);
            retPageVo.setPageNum(retLs.getPageNum());
            retPageVo.setPageSize(retLs.getPageSize());
            retPageVo.setTotal(retLs.getTotal());
            retPageVo.setList(retLs.getList());
        }
        if (op.equalsIgnoreCase("approve_review")) {
            HashMap<String, Object> approvecondition = new HashMap<String, Object>();
            approvecondition.put("user_id", user_id);
            approvecondition.put("apply_type", ptype);
            approvecondition.put("approve_type", 6);
            approvecondition.put("batch_id", batchInst.getId());

            if (strApplyStatus != null && (!strApplyStatus.isEmpty())) {
                int problem_stauts = Integer.parseInt(strApplyStatus);
                approvecondition.put("apply_status", problem_stauts);
            }

            if (matters != null && (!matters.isEmpty())) {
                approvecondition.put("matters", matters);
            }

            PageInfo<ScoreAddApplyEntity> retLs = scoreAddApplyService.getScoreAddApplyListByApproverPager(pgnum, pgsize, approvecondition);
            retPageVo.setPageNum(retLs.getPageNum());
            retPageVo.setPageSize(retLs.getPageSize());
            retPageVo.setTotal(retLs.getTotal());
            retPageVo.setList(retLs.getList());
        }
        if (op.equalsIgnoreCase("review")) {
            if (scoreAddApplyService.getApplyStage(batchInst) >= 1) {
                HashMap<String, Object> approvecondition = new HashMap<String, Object>();
                approvecondition.put("user_id", user_id);
                approvecondition.put("apply_type", ptype);
                approvecondition.put("approve_type", 4);
                approvecondition.put("batch_id", batchInst.getId());

                if (strApplyStatus != null && (!strApplyStatus.isEmpty())) {
                    int problem_stauts = Integer.parseInt(strApplyStatus);
                    approvecondition.put("apply_status", problem_stauts);
                }

                if (matters != null && (!matters.isEmpty())) {
                    approvecondition.put("matters", matters);
                }

                PageInfo<ScoreAddApplyEntity> retLs = scoreAddApplyService.getScoreAddApplyListByApproverPager(pgnum, pgsize, approvecondition);
                retPageVo.setPageNum(retLs.getPageNum());
                retPageVo.setPageSize(retLs.getPageSize());
                retPageVo.setTotal(retLs.getTotal());
                retPageVo.setList(retLs.getList());
            }
        }
        ResultVo retVo = ResultVoUtil.success("success", retPageVo);
        return retVo;
    }

    @GetMapping("/getAddApplyDetail")
    public ResultVo getAddApplyDetail(String applyid) {
        JSONObject applyObj = new JSONObject();
        ScoreAddApplyEntity en = scoreAddApplyService.getScoreAddApply(applyid);
        applyObj.put("apply_inst", en);
        Map<String, Object> historyCondition = new HashMap<String, Object>();
        historyCondition.put("obj_id", applyid);
        List<ObjHistoryEntity> historyLs = objHistoryService.getObjectHistory(historyCondition);
        applyObj.put("history", historyLs);

        ResultVo retVo = ResultVoUtil.success("success", applyObj);
        return retVo;
    }

    private void addApproveUsers(String op, JSONObject opObj, JSONObject problemObj) {

        if (op.equals("review")) {
            return;
        }
        JSONArray arr = opObj.getJSONArray("receivers");

        if (arr == null || arr.isEmpty()) {
            return;
        }
        int approve_type = 0;
        if (op.equals("create")) {
            approve_type = 3;
        }

        if (op.equals("check") && problemObj.getString("apply_type").equals("0")) {
            approve_type = 6;
        }
        if (op.equals("check") && problemObj.getString("apply_type").equals("1")) {
            approve_type = 4;
        }
        if (op.equals("approve_review")) {
            approve_type = 4;
        }

        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("problem_id", problemObj.getString("id"));
        condition.put("approve_type", approve_type);
        approveUserSelectService.deleteApproveUserSelect(condition);

        for (int i = 0; i < arr.size(); i++) {
            ApproveUserSelectEntity en = new ApproveUserSelectEntity();
            en.setProblem_id(problemObj.getString("id"));
            en.setUser_id(arr.getJSONObject(i).getString("user_id"));
            en.setUser_name(arr.getJSONObject(i).getString("user_name"));
            en.setApprove_type(approve_type);

            approveUserSelectService.addApproveUserSelect(en);
        }
    }

    private void addOpHistory(String op, JSONObject opObj, JSONObject problemObj) {
        ObjHistoryEntity hisEn = new ObjHistoryEntity();
        hisEn.setObj_id(problemObj.getString("id"));
        hisEn.setCreate_time(new Date());
        hisEn.setObj_type(1);

        if (op.equals("create")) {
            hisEn.setOp_event(op);
            hisEn.setOp_content("加分申请，申请加分" + problemObj.getString("score"));
            hisEn.setOp_userid(problemObj.getString("user_id"));
            hisEn.setOp_username(problemObj.getString("user_name"));
        }
        if (op.equals("check")) {
            hisEn.setOp_event(op);
            String opcontent = "加分审核";
            if (opObj.getString("approve_result").equals("1")) {

                if (problemObj.getString("apply_type").equals("1")) {
                    String asse_dept = problemObj.getString("asse_dept");
                    String apply_dept = problemObj.getString("apply_dept");
                    if (asse_dept.equals(apply_dept)) {
                        opcontent += "本部门审核本部门通过，流程结束";
                    } else {
                        opcontent += ",审核通过";
                    }
                } else {
                    opcontent += ",审核通过";
                }

            }
            if (opObj.getString("approve_result").equals("0")) {
                opcontent += ",审核拒绝。拒绝原因：" + opObj.getString("refuse_reason");
            }
            hisEn.setOp_content(opcontent);
            hisEn.setOp_userid(opObj.getString("approve_userid"));
            hisEn.setOp_username(opObj.getString("approve_username"));
        }
        if (op.equals("feedback_modify")) {
            hisEn.setOp_event(op);

            String opcontent = "加分申请修改，";
            if (opObj.getString("approve_result").equals("1")) {
                opcontent += ",结束加分申请";
            }
            if (opObj.getString("approve_result").equals("0")) {
                opcontent += "申请加分" + problemObj.getString("score");
            }

            hisEn.setOp_content(opcontent);
            hisEn.setOp_userid(problemObj.getString("user_id"));
            hisEn.setOp_username(problemObj.getString("user_name"));
        }
        if (op.equals("approve_review")) {
            hisEn.setOp_event(op);
            String opcontent = "加分复核";
            if (opObj.getString("approve_result").equals("1")) {
                opcontent += ",审核通过";
            }
            if (opObj.getString("approve_result").equals("0")) {
                opcontent += ",审核决绝。拒绝原因：" + opObj.getString("refuse_reason");
            }
            hisEn.setOp_content(opcontent);
            hisEn.setOp_userid(opObj.getString("approve_userid"));
            hisEn.setOp_username(opObj.getString("approve_username"));
        }
        if (op.equals("review")) {
            hisEn.setOp_event(op);
            String opcontent = "加分终审";
            if (opObj.getString("approve_result").equals("1")) {
                opcontent += ",审核通过";
            }
            if (opObj.getString("approve_result").equals("0")) {
                opcontent += ",审核决绝。拒绝原因：" + opObj.getString("refuse_reason");
            }
            hisEn.setOp_content(opcontent);
            hisEn.setOp_userid(opObj.getString("approve_userid"));
            hisEn.setOp_username(opObj.getString("approve_username"));
        }

        objHistoryService.addObjectHistory(hisEn);
    }

    private void sendImMessage(String op, JSONObject opObj, JSONObject problemObj) {
        int apply_type = Integer.parseInt(problemObj.getString("apply_type"));
        JSONArray arr = opObj.getJSONArray("receivers");
        //通知审核人
        List<String> ids = new ArrayList<>();
        if (arr != null && (!arr.isEmpty())) {
            for (int i = 0; i < arr.size(); i++) {
                ids.add(arr.getJSONObject(i).getString("user_id"));
            }
        }
        if (op.equals("create") || op.equals("feedback_modify")) {
            if (ids.size() > 0)
                wxSendMsgService.addScoreApplyCheckTipInfo(ids, apply_type);
        }
        if (op.equals("check")) {
            //审核通过，如果是公司对单位，通知局领导审核，如果审核不通过，通知申请人
            if (opObj.getString("approve_result").equals("1")) {
                if (ids.size() > 0) {
                    if (apply_type == 0)
                        wxSendMsgService.addScoreApplyApproveReviewTipInfo(ids, apply_type);
                    if (apply_type == 1) {
                        wxSendMsgService.addScoreApplyApproveLastReviewTipInfo(ids, apply_type);
                    }
                }
            }

            if (opObj.getString("approve_result").equals("0")) {
                ids.clear();
                ids.add(problemObj.getString("user_id"));
                wxSendMsgService.addScoreApplyCheckRejectTipInfo(ids, apply_type);
            }
        }

        if (op.equals("feedback_modify")) {
            //通知审核人
        }

        if (op.equals("approve_review")) {
            //审核不通过，通知申请人
            if (opObj.getString("approve_result").equals("0")) {
                ids.clear();
                ids.add(problemObj.getString("user_id"));
                wxSendMsgService.addScoreApplyCheckRejectTipInfo(ids, apply_type);
            } else if (opObj.getString("approve_result").equals("1")) {
                if (ids.size() > 0) {
                    wxSendMsgService.addScoreApplyApproveLastReviewTipInfo(ids, apply_type);
                }
            }
        }

//        if (op.equals("review")) {
//            //最终审核，拒绝通知申请人
//            if (opObj.getString("approve_result").equals("0")) {
//                ids.add(problemObj.getString("user_id"));
//                wxSendMsgService.addScoreApplyCheckRejectTipInfo(ids, apply_type);
//            }
//        }
    }
}
